package leetcodev1.树;

import leetcodev1.链表.Solution;

public class LeetCode108 {

    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        int n = nums.length;
        return dfs(nums, 0, n - 1, n);
    }

    private TreeNode dfs(int[] nums, int left, int right, int n) {
        if (left > right) {
            return null;
        }


        int mid = left + (right - left) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = dfs(nums, left, mid - 1, n);
        root.right = dfs(nums, mid + 1, right, n);
        return root;
    }
}

class Answer108{
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }

    public TreeNode helper(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }

        // 总是选择中间位置右边的数字作为根节点
        int mid = (left + right + 1) / 2;

        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        return root;
    }
}
